using System;
using System.Collections.Generic;
using System.IO;

namespace FileMapper {
    public abstract class FormatPlugin {
        private static ICollection<FormatPlugin> plugins = new HashSet<FormatPlugin>();

        public static void Register(FormatPlugin plugin) {
            plugins.Add(plugin);
        }

        public static void Unregister(FormatPlugin plugin) {
            plugins.Remove(plugin);
        }

        public static ExtentList ApplyPlugins(Stream file) {
            var result = new ExtentList { new Extent { Offset = 0, Size = file.Length } };
            foreach (var plugin in plugins) {
                var fs = file as FileStream;
                if ((fs == null || plugin.CheckName(fs.Name)) && plugin.CheckFormat(file)) {
                    result = result.Intersection(plugin.GetFixedExtents(file));
                }
            }
            return result;
        }

        protected virtual bool CheckName(string fileName) {
            return true;
        }

        protected virtual bool CheckFormat(Stream file) {
            return true;
        }

        protected virtual ExtentList GetFixedExtents(Stream file) {
            return new ExtentList { new Extent { Offset = 0, Size = file.Length } };
        }
    }
}
